package jobs

import (
	"bytes"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"github.com/goburrow/modbus"
	"net/http"
	"time"
	"water-temperature-server/config"
	"water-temperature-server/utils"
)

func StartSyncData(clientHandler *modbus.TCPClientHandler) {
	tm := time.Now().Format("2006-01-02 15:04:05")
	for ChannelNo := 14; ChannelNo >= 1; ChannelNo-- {
		SensorIndex := 1
		DeviceNum := 15
		if ChannelNo == 13 {
			DeviceNum = 10
		} else if ChannelNo == 14 {
			DeviceNum = 5
		}
		hexData, hexDataErr := utils.ReadDeviceData(ChannelNo, SensorIndex, 1, DeviceNum)
		if hexDataErr != nil {
			fmt.Printf("数据转换错误:%v\n", hexDataErr)
			continue
		}
		send, errSend := clientHandler.Send(hexData)
		if errSend != nil {
			fmt.Printf("数据发送异常:%v\n", errSend)
			continue
		} else {
			deviceData := utils.ParseData(hex.EncodeToString(send), ChannelNo, SensorIndex, tm)
			if len(*deviceData) != 0 {
				//temperatureService.InsetBatch(deviceData)
				bytesData, _ := json.Marshal(deviceData)
				resp, err := http.Post(config.GlobalConfigSetting.DataUrl, "application/json", bytes.NewReader(bytesData))
				defer resp.Body.Close()
				if err != nil {
					fmt.Println(err)
				} else {
				}
			}
		}
	}

}
